package com.tudouji.project.produce.service.impl;

import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.ResultParam;
import com.flow.service.pojo.result.FlowResult;
import com.flow.service.process.service.IFlowBaseService;
import com.github.pagehelper.PageHelper;
import com.tudouji.common.enums.WhoutformTypeEnums;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.common.utils.sql.SqlUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.PageDomain;
import com.tudouji.framework.web.page.TableSupport;
import com.tudouji.project.bill.domain.*;
import com.tudouji.project.bill.mapper.WhinformMapper;
import com.tudouji.project.bill.mapper.WhoutformMapper;
import com.tudouji.project.bill.service.impl.WhoutformServiceImpl;
import com.tudouji.project.flow.utils.FlowProcessUtil;
import com.tudouji.project.harvest.domain.Qaform;
import com.tudouji.project.harvest.mapper.QaformMapper;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.mapper.DepartmentMapper;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.impl.SalespermissionServiceImpl;
import com.tudouji.project.produce.domain.*;
import com.tudouji.project.produce.mapper.*;
import com.tudouji.project.produce.service.IPickinglistService;
import com.tudouji.project.produce.service.IPickinglistitemService;
import com.tudouji.project.product.domain.Brand;
import com.tudouji.project.product.domain.Productinfo;
import com.tudouji.project.product.domain.Products;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.product.mapper.BrandMapper;
import com.tudouji.project.product.mapper.ProductinfoMapper;
import com.tudouji.project.product.mapper.ProductsMapper;
import com.tudouji.project.product.mapper.SalesspecificationMapper;
import com.tudouji.project.store.domain.Stockunit;
import com.tudouji.project.store.domain.Storehouseroom;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.mapper.StockunitMapper;
import com.tudouji.project.store.mapper.StorehouseroomMapper;
import com.tudouji.project.store.mapper.StoreroomMapper;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.domain.Upimage;
import com.tudouji.project.system.mapper.UpimageMapper;
import com.tudouji.project.system.service.ISysConfigService;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;

/**
 * 领料单Service业务层处理
 *
 * @author tudouji
 * @date 2022-06-01
 */
@Service
public class PickinglistServiceImpl implements IPickinglistService, IFlowBaseService {
    @Autowired
    private PickinglistMapper pickinglistMapper;
    @Autowired
    private ProduceplanMapper produceplanMapper;
    @Autowired
    private StoreroomMapper storeroomMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private StorehouseroomMapper storehouseroomMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private BusinesscodeServiceImpl businesscodeService;
    @Autowired
    private ProductinfoMapper productinfoMapper;
    @Autowired
    private StockunitMapper stockunitMapper;
    @Autowired
    private WhoutformServiceImpl whoutformService;
    @Autowired
    private WhoutformMapper whoutformMapper;
    @Autowired
    private PickinglistitemMapper pickinglistitemMapper;
    @Autowired
    private FlowProcessUtil processUtils;
    @Autowired
    private SalespermissionServiceImpl permissionService;
    @Autowired
    private WhinapplyMapper whinapplyMapper;
    @Autowired
    private ScrapapplyMapper scrapapplyMapper;
    @Autowired
    private MaterialretapplyMapper materialretapplyMapper;
    @Autowired
    private SalesspecificationMapper salesspecificationMapper;
    @Autowired
    private WhinformMapper whinformMapper;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private QaformMapper qaformMapper;
    @Autowired
    private UpimageMapper upimageMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private IPickinglistitemService pickinglistitemService;

    /**
     * 查询领料单
     *
     * @param guid 领料单ID
     * @return 领料单
     */
    @Override
    public Pickinglist selectPickinglistById(String guid) {
        return pickinglistMapper.selectPickinglistById(guid);
    }


    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (com.tudouji.common.utils.StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 查询领料单列表
     *
     * @param pickinglist 领料单
     * @return 领料单
     */
    @Override
    public List<Pickinglist> selectPickinglistList(Pickinglist pickinglist, String status, String functionType) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<Pickinglist> list;
        if (pickinglist == null) {
            pickinglist = new Pickinglist();
        }

        if (org.apache.commons.lang.StringUtils.isNotBlank(status)) {
            // 待处理
            if (status.equals("00")) {
                startPage();
                pickinglist.setCreateBy(sysUser.getUserId());
                return pickinglistMapper.selectApplyPendingList(pickinglist);
            } else {
                String[] sts = status.split(",");
                Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
                pickinglist.setStats(stss);
            }
        }
        //查询是否有全局权限
        List<Salespermission> permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "4");
        if (permissions.size() > 0) {
            startPage();
            pickinglist.setStats(null);
            list = pickinglistMapper.selectPickinglistList(pickinglist);
        } else {
            pickinglist.setCreateBy(sysUser.getUserId());
            // 是否有组织权限
            List<Salespermission> permissionsOrg = permissionService
                    .getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "7");
            //是否有组织+部门权限
            permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "3");

            startPage();
            if (permissions.size() > 0 || permissionsOrg.size() > 0) {
                String[] androomids = new String[permissions.size()];
                String[] anddepids = new String[permissions.size()];
                for (int i = 0; i < permissions.size(); i++) {
                    androomids[i] = permissions.get(i).getSrguid();
                    anddepids[i] = permissions.get(i).getDepartid();
                }
                String[] roomids = new String[permissionsOrg.size()];
                for (int i = 0; i < permissionsOrg.size(); i++) {
                    roomids[i] = permissionsOrg.get(i).getSrguid();
                }
//                pickinglist.setRoomids(roomids);
//                pickinglist.setDepartids(deptids);
                pickinglist.setOrgIds(roomids);

                pickinglist.setAndorgIds(androomids);
                pickinglist.setAnddeptIds(anddepids);
                list = pickinglistMapper.selectPickinglistByPerm(pickinglist);
            } else {
                //查询个人的
                list = pickinglistMapper.selectPickinglistByUser(pickinglist);
            }
        }
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Pickinglist listItem = list.get(i);
                listItem.setMaterialretapplyCount(pickinglistMapper.materialretapplyCount(listItem.getGuid()) + "");
                listItem.setScrapapplyCount(pickinglistMapper.scrapapplyCount(listItem.getGuid()) + "");
                listItem.setWhinapplyCount(pickinglistMapper.whinapplyCount(listItem.getGuid()) + "");
            }
        }
        return list;
    }

    /**
     * 查询领料单列表
     *
     * @param pickinglist 领料单
     * @return 领料单
     */
    @Override
    public List<Pickinglist> selectPickinglistList(Pickinglist pickinglist) {
        return pickinglistMapper.selectPickinglistList(pickinglist);
    }
    @Override
    public List<Pickinglist> selectPickinglistListPc(Pickinglist pickinglist) {
        return pickinglistMapper.selectPickinglistListPc(pickinglist);
    }

    /**
     * 新增领料单
     *
     * @param pickinglist 领料单
     * @return 结果
     */
    @Override
    public int insertPickinglist(Pickinglist pickinglist) {
        return pickinglistMapper.insertPickinglist(pickinglist);
    }

    /**
     * 修改领料单
     *
     * @param pickinglist 领料单
     * @return 结果
     */
    @Override
    public int updatePickinglist(Pickinglist pickinglist) {
        return pickinglistMapper.updatePickinglist(pickinglist);
    }

    /**
     * 批量删除领料单
     *
     * @param guids 需要删除的领料单ID
     * @return 结果
     */
    @Override
    public int deletePickinglistByIds(String[] guids) {
        return pickinglistMapper.deletePickinglistByIds(guids);
    }

    /**
     * 删除领料单信息
     *
     * @param guid 领料单ID
     * @return 结果
     */
    @Override
    public int deletePickinglistById(String guid) {
        return pickinglistMapper.deletePickinglistById(guid);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult save(Pickinglist pickinglist, String fileIds) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        // 组装领料单数据
        pickinglist.setOperatorid(sysUser.getTuserId());
        pickinglist.setFlowid("30");

        Storeroom room = storeroomMapper.selectStoreroomByGuid(pickinglist.getStrmid());
        Organization org = organizationMapper.selectOrganizationById(room.getOrgguid());
        pickinglist.setOrgid(room.getOrgguid());
        pickinglist.setOrgId(org.getId());
        pickinglist.setOrgname(room.getOrgname());
        pickinglist.setStrm(room.getId());

        Department department = departmentMapper.selectDepartmentById(pickinglist.getDepartmentid());
        pickinglist.setDeptId(department.getId());
        pickinglist.setDeptName(department.getName());

        // 生成编码
        pickinglist.setCode(businesscodeService.getCode("18"));
        String guid = IdUtils.fastSimpleUUID();
        pickinglist.setGuid(guid);
        pickinglist.setCreatetime(DateUtils.getNowDate());
        pickinglist.setCreateBy(sysUser.getUserId());
        pickinglist.setStatus(-1);
        pickinglistMapper.insertPickinglist(pickinglist);

        BigDecimal weightSum = BigDecimal.ZERO;
        for (Pickinglistitem item : pickinglist.getItems()) {
            item.setStrmid(pickinglist.getStrmid());
            item.setPickinglistid(guid);
            // 查询产品
            Productinfo product = productinfoMapper.selectProductinfoById(item.getProductid());
            item.setProduct(product.getProductname());
            Stockunit skunit = stockunitMapper.selectStockunitById(item.getStockunitid());
            if (item.getPicktype() != 4) {
                try {
                    weightSum = weightSum.add(whoutformService.calculateWeight(item.getSpeid(), item.getWeight(), null, 3).get("toT"));
                } catch (Exception e) {
                    e.printStackTrace();
                    return AjaxResult.error();
                }
            }
            item.setGuid(IdUtils.fastSimpleUUID());
            item.setCreateTime(DateUtils.getNowDate());
            item.setCreateBy(sysUser.getUserId());
            pickinglistitemMapper.insertPickinglistitem(item);
        }

        Pickinglist pl = new Pickinglist();
        pl.setGuid(guid);
        pl.setWeightsum(weightSum);

        pickinglist.setPlatformId(room.getId());
        FlowResult result = processUtils.defaultStart(processUtils.getStartNode(Long.parseLong(pickinglist.getFlowid()))
                , pickinglist, fileIds, sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            pl.setStatus(result.getNextStat());
            pickinglistMapper.updatePickinglist(pl);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult approval(Long id, String imgids, String opinion, Long taskid) {

        Pickinglist pickinglist = pickinglistMapper.selectPickinglistByNewId(id);

        Storeroom storeroomFrom = storeroomMapper.selectStoreroomByGuid(pickinglist.getStrmid());
//        pickinglist.setOrgId(Long.valueOf(storeroomFrom.getId()));

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        pickinglist.setPlatformId(storeroomFrom.getId());
        FlowResult result = processUtils.defaultApproval(taskid, imgids, opinion, pickinglist
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Pickinglist pb = new Pickinglist();
            pb.setStatus(result.getNextStat());
            pb.setGuid(pickinglist.getGuid());
            this.updatePickinglist(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult refuse(Long id, String fileIds, String opinion, Long taskid, Long refuseNodeid, Long backUserid) {
        Pickinglist pickinglist = pickinglistMapper.selectPickinglistByNewId(id);

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        pickinglist.setPlatformId(pickinglist.getStrm());
        FlowResult result = processUtils.defaultRefuse(taskid, fileIds, opinion, pickinglist
                , sysUser, refuseNodeid, backUserid);

        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Pickinglist pb = new Pickinglist();
            pb.setStatus(result.getNextStat());
            pb.setGuid(pickinglist.getGuid());
            this.updatePickinglist(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    public AjaxResult del(Long id) {
        Pickinglist pickinglist = pickinglistMapper.selectPickinglistByNewId(id);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (pickinglist.getStatus() <= 10) {
            pickinglist.setStatus(0);
            pickinglistMapper.updatePickinglistNew(pickinglist);
            //更新待处理任务
            processUtils.updateTaskByOrderId(id, sysUser, Long.parseLong(pickinglist.getFlowid()));
            return AjaxResult.success();
        } else {
            return AjaxResult.error("已出库！");
        }
    }

    @Override
    public AjaxResult getInfo(Long id) {
        AjaxResult result = AjaxResult.success();
        Pickinglist pickinglist = pickinglistMapper.getInfo(id);
        result.put("data", pickinglist);

        // 查询领料单报废登记数据
        Scrapapply scrap = new Scrapapply();
        scrap.setPickinglistid(pickinglist.getGuid());
        scrap.setType(3);
        scrap.setStatus(100);
        List<Scrapapply> scraps = scrapapplyMapper.findDetail(scrap);
        result.put("scraps", scraps);
        // 查询报废登记重量
        Double scrapweight = scrapapplyMapper.getSumWeight(scrap);

        result.put("scrapweight", String.format("%.2f", scrapweight));

        // 入库申请单数据-->查询入库数据
        Whinapply whinapply = new Whinapply();
        whinapply.setPickinglistid(pickinglist.getGuid());
        List<Whinapply> ws = whinapplyMapper.selectWhinapplyList(whinapply);
        if (ws.size() > 0) {
            String[] whinapplyids = new String[ws.size()];
            for (int i = 0; i < ws.size(); i++) {
                whinapplyids[i] = ws.get(i).getGuid();
            }
            // 产成品 入库信息
            Whinform whinform = new Whinform();
            whinform.setOrderids(whinapplyids);
            whinform.setWhintype(4);
            List<Whinform> whinforms = whinformMapper.findDetail(whinform);
            result.put("whinforms", whinforms);
            // 查询产成品重量
            Double whinformweight = whinformMapper.getSumWeight(whinform);
            result.put("whinformweight", whinformweight);

            // 不合格入库信息
            Whinform wh = new Whinform();
            wh.setOrderids(whinapplyids);

            wh.setWhintype(5);
            List<Whinform> failedwhs = whinformMapper.findDetail(wh);
            result.put("failedwhs", failedwhs);

            // 查询不合格重量
            Double failedweight = whinformMapper.getSumWeight(wh);
            result.put("failedweight", failedweight);
        }
        // 出库单
        Whoutform outform = new Whoutform();
        outform.setOrderguid(pickinglist.getGuid());
        outform.setOuttype(4);
        List<Whoutform> outforms = whoutformService.findDetail(outform);
        //查询成本对象
        if (pickinglist.getPicktype() == 2) {//辅料领取的时候需要查询出库单明细中的成本对象  展示
            for (Whoutform w : outforms) {
                for (Whoutformitem i : w.getItems()) {
                    Salesspecification sp = new Salesspecification();
                    sp.setGuid(i.getCospguid());
                    sp = salesspecificationMapper.selectSalesspecificationById(i.getCospguid());
                    i.setCosobj(sp);
                }
            }
        }
        result.put("outforms", outforms);
        // 查询出库重量
        Double outweight = whoutformMapper.getSumweight(outform);
        result.put("outweight", outweight);

        // 退料单
        Materialretapply mater = new Materialretapply();
        mater.setLinkedid(pickinglist.getGuid());
        List<Materialretapply> maters = materialretapplyMapper.selectMaterialretapplyList(mater);
        result.put("maters", maters);
        if (maters.size() > 0) {
            // 退料单重量统计
            Whinform whf = new Whinform();
            String[] ids = new String[maters.size()];
            for (int i = 0; i < maters.size(); i++) {
                ids[i] = maters.get(i).getGuid();
            }
            whf.setOrderids(ids);
            whf.setWhintype(6);
            Double materweight = whinformMapper.getSumWeight(whf);
            result.put("materweight", materweight);
        }
        /**
         * 2019-12-3 领料单详细中加入质检但数据，以及质检单图片
         *
         * @author liukx
         *
         */

        Qaform qa = new Qaform();
        qa.setFoguid(pickinglist.getGuid());
        qa = qaformMapper.selectQaformByFoguid(pickinglist.getGuid());
        result.put("qaForm", qa);
        // 质检单图片
        Upimage upimage = new Upimage();
        upimage.setImagename("质检");
        upimage.setImagetype("QA");
        upimage.setEvidenceguid(pickinglist.getGuid());
        result.put("qaFormImg", upimageMapper.selectUpimageList(upimage));
        return result;
    }

    @Override
    public AjaxResult getBaseInfo(String planid) {
        AjaxResult result = AjaxResult.success();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        // 获取生产计划及明细
        Produceplan plan = produceplanMapper.findDetail(planid);
        result.put("plan", plan);

        Productinfo productinfo = new Productinfo();
        productinfo.setGuid(plan.getStrmid());
        productinfo.setOrgguid(plan.getOrgid());
        List<Productinfo> products = productinfoMapper.findProductinfoBYStr(productinfo);
        result.put("products", products);

        // 获取有发布领料单权限的班组信息
        List<Salespermission> permissions = permissionService.getPermBySrOrDepart(sysUser.getUserId(), null,
                "3", plan.getStrmid(), null);
        String[] depids = new String[permissions.size()];
        if (permissions.size() > 0) {
            for (int i = 0; i < permissions.size(); i++) {
                depids[i] = permissions.get(i).getDepartid();
            }
            Department depart = new Department();
            depart.setIds(depids);
            depart.setStatus(1);
            List<Department> departs = departmentMapper.selectDepartmentList(depart);
            result.put("departs", departs);
        }
        return result;
    }

    @Override
    public Pickinglist selectPickinglistByNewId(Long pickinglistid) {
        return pickinglistMapper.selectPickinglistByNewId(pickinglistid);
    }

    @Override
    public AjaxResult getSpes(Long pickid, String productid) {
        Pickinglist picking = pickinglistMapper.selectPickinglistByNewId(pickid);
        Pickinglistitem item = new Pickinglistitem();
        item.setPickinglistid(picking.getGuid());
        if (StringUtils.isNotEmpty(productid)) {
            item.setProductid(productid);
        }

        List<Pickinglistitem> items = pickinglistitemMapper.findSpe(item);
        return AjaxResult.success(items);
    }

    @Override
    public AjaxResult getProducts(Long pickinglistid) {
        AjaxResult result = AjaxResult.success();
        // 查询领料单
        Pickinglist picking = pickinglistMapper.selectPickinglistByNewId(pickinglistid);
        result.put("pickinglist", picking);

        // 领料单明细
        Pickinglistitem item = new Pickinglistitem();
        item.setPickinglistid(picking.getGuid());
        List<Pickinglistitem> itemss = pickinglistitemMapper.selectPickinglistitemList(item);
        result.put("items", itemss);

        // 查询领料单明细中的产品信息 --去重
        Pickinglistitem product = new Pickinglistitem();
        product.setPickinglistid(picking.getGuid());
        List<Products> products = pickinglistitemMapper.findProducts(product);
        result.put("products", products);
        return result;
    }

    @Override
    public List<Pickinglist> findCollect(Pickinglist plDetail) {
        return pickinglistMapper.findCollect(plDetail);
    }

    @Override
    public List<Pickinglist> findPPDetail(Pickinglist plDetail) {
        return pickinglistMapper.findPPDetail(plDetail);
    }

    @Override
    public AjaxResult getCosproduct(String strguid, String productflag) {
        AjaxResult result = AjaxResult.success();
        Storeroom room = storeroomMapper.selectStoreroomByGuid(strguid);
        String categoryid = room.getCategoryids();
        if (org.apache.commons.lang.StringUtils.isNotBlank(categoryid)) {
            String[] categoryids = categoryid.split(",");
            // 查找品牌
            Brand brand = new Brand();
            brand.setCategoryids(categoryids);
            List<Brand> brands = brandMapper.selectBrandList(brand);
            String[] brandids = new String[brands.size()];
            for (int i = 0; i < brands.size(); i++) {
                brandids[i] = brands.get(i).getGuid();
            }
            Products pro = new Products();
            pro.setBrandids(brandids);
            pro.setProflags(productflag.split(","));
            pro.setStats(new Integer[]{1});
            List<Products> proList = productsMapper.getProByType(pro);
            result.put("products", proList);
        }
        return result;
    }

    /**
     * 领料单出库操作
     * @param id           领料单Id
     * @param entity       出库单
     * @param fileIds      上传附件
     * @param opinion      审批意见
     * @param taskid       审批任务Id
     * @param opttype      操作类型，没用了
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult whout(Long id, Whoutform entity, String fileIds, String opinion, Long taskid, String opttype){
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<Whoutformitem> items = entity.getItems();

        BigDecimal pricesum = new BigDecimal(0);
        // 查询领料单
        Pickinglist pickinglist = pickinglistMapper.findDetail(id);

        entity.setDepartmentid(pickinglist.getDepartmentid());
        //准备出库单主表数据
        prepareWhoutform(entity,pickinglist,sysUser);

        //出库
        whoutformService.whout(entity,items,false,null);
        //出库后更新领料单明细数据
        for (Whoutformitem item : items) {
            // 根据出库明细数据更新领料单明细
            BigDecimal priceitem = pickinglistitemService.updatePIAfterWhout(item);
            pricesum = pricesum.add(priceitem);
        }

        FlowResult result = processUtils.defaultApproval(taskid, fileIds, opinion, pickinglist
                , sysUser);

        Pickinglist sfo = new Pickinglist();
        sfo.setGuid(pickinglist.getGuid());
        sfo.setLastupdate(new Date());
        sfo.setWeightsum(entity.getWeight());
        sfo.setPricesum(pricesum);
        sfo.setStatus(result.getNextStat());
        pickinglistMapper.updatePickinglist(sfo);

        return AjaxResult.success();
    }

    private void prepareWhoutform(Whoutform entity, Pickinglist pickingList,SysUser user) {
        // 出库单数据组装
        entity.setOrderguid(pickingList.getGuid());
        entity.setBusinesscode(pickingList.getCode());
        entity.setIsCopytoKD(1);
        entity.setOuttype(WhoutformTypeEnums.PRODUCTION.getCode());
        entity.setSrguid(pickingList.getStrmid());
        entity.setOperatorid(user.getGuid());
        entity.setOuttime(DateUtils.getNowDate());
    }

    public AjaxResult checkWeight(String pickinglistid, BigDecimal nowWeight) {
        Pickinglist pick = new Pickinglist();
        String[] ids = {pickinglistid};
        pick.setIds(ids);

        // 获取出库重量
        BigDecimal outWeight = BigDecimal.ZERO;
        Whoutform out = new Whoutform();
        out.setOrderguid(pickinglistid);
        List<Whoutform> outs = whoutformService.findDetail(out);
        if (outs.size() > 0) {
            out = outs.get(0);
        }
        for (Whoutformitem i : out.getItems()) {
            Storehouseroom house = storehouseroomMapper.selectStorehouseroomById(i.getShrguid());
            if (house.getShrtype() != 4) {//辅料不参与计算
                outWeight = outWeight.add(whoutformService.calculateWeight(i.getSpguid(), i.getWeight(), null, 3).get("toT"));
            }
        }

        // 入库重量
        BigDecimal inWeight = BigDecimal.ZERO;
        //查询入库单
        Whinapply apply = new Whinapply();
        apply.setStatus(3);
        apply.setPickinglistid(pickinglistid);
        List<Whinapply> applys = whinapplyMapper.selectWhinapplyList(apply);
        if (applys.size() > 0) {
            String[] applyids = new String[applys.size()];
            for (int i = 0; i < applys.size(); i++) {
                applyids[i] = applys.get(i).getGuid();
            }
            Whinform in = new Whinform();
            in.setOrderids(applyids);
            List<Whinform> ins = whinapplyMapper.findDetail(in);
            for (Whinform wi : ins) {
                for (Whinformitem it : wi.getItems()) {
                    Storehouseroom house = storehouseroomMapper.selectStorehouseroomById(it.getShrguid());
                    if (house.getShrtype() != 4) {//辅料不参与计算
                        inWeight = inWeight.add(whoutformService.calculateWeight(it.getSpguid(), it.getWeight(), null, 3).get("toT"));
                    }
                }
            }
        }

        System.out.println("---------inWeight:" + inWeight);
        // 报废重量
        BigDecimal scrapWeight = BigDecimal.ZERO;
        Scrapapply sa = new Scrapapply();
        sa.setPickinglistid(pickinglistid);
        List<Scrapapply> sas = scrapapplyMapper.findDetail(sa);
        if (sas.size() > 0) {
            for (Scrapapply sc : sas) {
                if (sc.getStatus() != 6) {
                    for (Scrapapplyitem si : sc.getItems()) {
                        Salesspecification spe = salesspecificationMapper.selectSalesspecificationById(si.getSpecguid());
                        if (spe.getType() != 4) {//辅料不参与计算
                            scrapWeight = scrapWeight.add(whoutformService.calculateWeight(si.getSpecguid(), si.getWeight(), null, 3).get("toT"));
                        }
                    }
                }
            }
        }

        System.out.println("---------scrapWeight:" + scrapWeight);
        // 退料重量
        BigDecimal returnWeight = BigDecimal.ZERO;
        Materialretapply ma = new Materialretapply();
        ma.setLinkedid(pickinglistid);
        List<Materialretapply> mas = materialretapplyMapper.selectMaterialretapplyList(ma);
        if (mas.size() > 0) {
            String[] masids = new String[mas.size()];
            for (Materialretapply m : mas) {
                for (int i = 0; i < mas.size(); i++) {
                    masids[i] = mas.get(i).getGuid();
                }
                Whinform in = new Whinform();
                in.setOrderids(masids);
                List<Whinform> ins = whinformMapper.findDetail(in);
                for (Whinform wi : ins) {
                    for (Whinformitem it : wi.getItems()) {
                        Salesspecification spe = salesspecificationMapper.selectSalesspecificationById(it.getSpguid());
                        if (spe.getType() != 4) {//辅料不参与计算
                            returnWeight = returnWeight.add(whoutformService.calculateWeight(it.getSpguid(), it.getWeight(), null, 3).get("toT"));
                        }
                    }
                }
            }
        }
        outWeight = outWeight.multiply(new BigDecimal(this.sysConfigService.selectConfigByKey("pickinglist_weight_param")));

        System.out.println("____________________" + outWeight);
        System.out.println(outWeight.subtract(inWeight).subtract(scrapWeight).subtract(returnWeight).subtract(nowWeight));
        if (outWeight.compareTo(BigDecimal.ZERO) == -1) {//领出料为负
            if ((outWeight.subtract(inWeight).subtract(scrapWeight).subtract(returnWeight).subtract(nowWeight))
                    .compareTo(BigDecimal.ZERO) != 1) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("超出最大出库重量");
            }
        } else {
            if ((outWeight.subtract(inWeight).subtract(scrapWeight).subtract(returnWeight).subtract(nowWeight))
                    .compareTo(BigDecimal.ZERO) != -1) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("超出最大出库重量");
//                result="overWeight";
            }
        }
    }

    @Override
    public BasePojo getBaseById(Long id) {
        return selectPickinglistByNewId(id);
    }

    @Override
    public BasePojo getBaseByCode(String code) {
        return null;
    }
}
